package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(this.getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenusById(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }


//    @Caching(evict = {@CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")})
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        //首先，先更新自己
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("正在使用缓存");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    //TODO 产生堆外内存溢出异常
    @Cacheable(value = "category", key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        List<CategoryEntity> selectAll = baseMapper.selectList(null);
        //1.查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectAll, 0L);
        //2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //1.查询每一个一级分类，再调用方法找到该分类底下的二级分类(得到的是CategoryEntity而不是 Catelog2Vo)
            List<CategoryEntity> categoryEntities = getParent_cid(selectAll, v.getCatId());
            //2.判断categoryEntities 是否存在
            if (categoryEntities != null && categoryEntities.size() > 0) {
                //3.把CategoryEntity 封装成 Catelog2Vo
                List<Catelog2Vo> catelog2Vos = categoryEntities.stream().map((lv_2 -> {
                    //4.对于任意一个Catelog2Vo ，查出其的三级子分类
                    List<CategoryEntity> category_lv3 = getParent_cid(selectAll, lv_2.getCatId());
                    //5.判断是否为空
                    List<Catelog2Vo.Catelog3Vo> catelog3VoList = null;
                    if (category_lv3 != null && category_lv3.size() > 0) {
                        //把子分类封装成vo
                        catelog3VoList = category_lv3.stream().map(lv_3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(lv_3.getParentCid().toString());
                            catelog3Vo.setId(lv_3.getCatId().toString());
                            catelog3Vo.setName(lv_3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), catelog3VoList, lv_2.getCatId().toString(), lv_2.getName());
                    return catelog2Vo;
                })).collect(Collectors.toList());
                return catelog2Vos;
            } else {
                return null;
            }
        }));
        return parent_cid;

    }

    //TODO 产生堆外内存溢出异常
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //json与能用的对象互相转化

        //1.加入缓存逻辑
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");

        if (StringUtils.isEmpty(catalogJson)) {
            //2.缓存中没有,查询数据库

            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromRedissonLockDB();

            return catalogJsonFromDB;
        }
        //redis中命中，转化为Map集合
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });

        return result;


    }

    /**
     * 使用分布式锁 redisson
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromRedissonLockDB() {
        //1.占分布式锁。注意锁的名字
        RLock lock = redisson.getLock("catalogJson_lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB;

        try {
            //加锁成功-执行业务
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    /**
     * 使用redis锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromRedisLockDB() {
        String uuid_string = UUID.randomUUID().toString();
        //1.占分布式锁。
        Boolean locked = stringRedisTemplate.opsForValue().setIfAbsent("locked", uuid_string, 300, TimeUnit.SECONDS);
        if (locked) {
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                //加锁成功-执行业务
                dataFromDB = getDataFromDB();
            } finally {
                //调用lua脚本删除locked
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //删除锁
                Long locked1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("locked", uuid_string));
            }
            return dataFromDB;

        } else {
            //没成功---重试
            //休眠200毫秒
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromRedisLockDB();
        }


    }

    /**
     * 从数据库查询并封装
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromLocalLockDB() {

        synchronized (this) {
            return getDataFromDB();
        }
    }

    /**
     * 将集合的多重查询变为一次
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
        return collect;
    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");

        if (!StringUtils.isEmpty(catalogJson)) {
            //判断是否为空：存在则进
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        List<CategoryEntity> selectAll = baseMapper.selectList(null);
        //1.查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectAll, 0L);
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //1.查询每一个一级分类，再调用方法找到该分类底下的二级分类(得到的是CategoryEntity而不是 Catelog2Vo)
            List<CategoryEntity> categoryEntities = getParent_cid(selectAll, v.getCatId());
            //2.判断categoryEntities 是否存在
            if (categoryEntities != null && categoryEntities.size() > 0) {
                //3.把CategoryEntity 封装成 Catelog2Vo
                List<Catelog2Vo> catelog2Vos = categoryEntities.stream().map((lv_2 -> {
                    //4.对于任意一个Catelog2Vo ，查出其的三级子分类
                    List<CategoryEntity> category_lv3 = getParent_cid(selectAll, lv_2.getCatId());
                    //5.判断是否为空
                    List<Catelog2Vo.Catelog3Vo> catelog3VoList = null;
                    if (category_lv3 != null && category_lv3.size() > 0) {
                        //把子分类封装成vo
                        catelog3VoList = category_lv3.stream().map(lv_3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(lv_3.getParentCid().toString());
                            catelog3Vo.setId(lv_3.getCatId().toString());
                            catelog3Vo.setName(lv_3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), catelog3VoList, lv_2.getCatId().toString(), lv_2.getName());
                    return catelog2Vo;
                })).collect(Collectors.toList());
                return catelog2Vos;
            } else {
                return null;
            }
        }));

        //3.查到的数据再换入缓存，将对象转为json放在缓存中
        String s = JSON.toJSONString(parent_cid);
        stringRedisTemplate.opsForValue().set("catalogJson", s, 1, TimeUnit.DAYS);

        return parent_cid;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //收集当前节点的ID
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            categoryEntity.setChildren(this.getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}